﻿using _111.Models;
using _111.QywxDocument.DigitalizationDemand.Model;
using guidHelper;
using MyDapperApi.Models;
using MyDapperApi.Services.QywxBase;
using Newtonsoft.Json;
using QYWXUpdate.DataModel;
using QYWXUpdate.DataModel.QYWXDocument;
using static MyDapperApi.Services.DateBaseService;

namespace MyDapperApi.Services.QywxDocument.DigitalizationDemand;
public class DocDigitalizationDemandService : IDocDigitalizationDemandService
{
    private readonly IConfiguration _configuration;
    private readonly IHttpClientFactory _httpClientFactory;
    private readonly IDateBaseService _dateBaseService;
    private readonly IQywxBaseService _qywxBaseService;
    public readonly ICsvService _csvService;
    private readonly string _qywxReceiveToken = "sdas";
    private readonly string _corpId;
    private readonly INetUpdateService _netUpdateService;

    public DocDigitalizationDemandService(IHttpClientFactory httpClientFactory,
        IConfiguration configuration,
        IDateBaseService dateBaseService,
        ICsvService csvService,
        IQywxBaseService qywxBaseService,
        INetUpdateService netUpdateService)
    {
        _configuration = configuration;
        _httpClientFactory = httpClientFactory;
        _dateBaseService = dateBaseService;
        _csvService = csvService;
        _corpId = configuration["QywxSettings:CorpId"];
        _qywxBaseService = qywxBaseService;
        _netUpdateService = netUpdateService;
    }

    #region 企业数字化需求表格
    
    public async Task<CommonResponse> ClearDataBaseDigitalizationDemand()
    {
        var result = new CommonResponse();

        var sql = "TRUNCATE TABLE digitalization_demand";
        var sqlBuilder = new SqlBuilder();

        result = await _dateBaseService.ExecuteAsync(sql, sqlBuilder);

        result = await UpdateDataBaseDigitalizationDemand(0, 100);

        result = await GetHasFinishedNumber();

        result.SetSuccess();
        return result;
    }

    public async Task<CommonResponse> UpdateDataBaseDigitalizationDemand(int offset,int limit)
    {
        var result = new CommonResponse();
        //var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        //var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = "dcPfyR993e_EoTVs6XGZFI8ayHf68-WD-tAPeCZeAX2rFfKeMPq3iSHCWZgI_QyEOxuVjJ2XXhUdClRzYUtfXR5g",
            sheet_id = "tlHpWX",
            offset = offset,
            limit = limit
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var wxResponse = await _qywxBaseService.QywxDocumentPost<SaveDigitalizationDemandRecordDetail>(content, "https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/get_records?access_token=");
        if (wxResponse.records.Count > 0)
        {
            foreach (var item in wxResponse.records)
            {
                var current = string.Empty;
                if (item.values.当前状态 != null)
                {
                    current = item.values.当前状态[0].text;
                }
                var tempItem = new DigitalizationDemandEntity()
                {
                    Id = ToolHelper.GUIDTO16(),
                    Is_Deleted = 0,
                    Created_On = DateTime.Now,
                    Modified_On = DateTime.Now,
                    Record_Id = item.record_id,
                    Current_Status = getStatus(current),
                };
                //CsvList.Add(tempItem);

                result = await CheckDateBase(tempItem);
            }
            result.SetSuccess();
            return result;
        }
        if (wxResponse.has_more)
        {
            await UpdateDataBaseDigitalizationDemand(wxResponse.next,100);
        }

        return result;
    }

    public async Task<CommonResponse> UpdateQywxWorkBanch(string recordId)
    {
        var result = new CommonResponse();
        //var token = await _qywxBaseService.GetAccessTokenAsync("ww41ce2a97523f4d1a", "xKW0MRSs9azutLLPJt2hDi6gtpYDpdeas5azgxcbUnQ");
        //var client = _httpClientFactory.CreateClient();

        var content1 = new
        {
            docid = "dcPfyR993e_EoTVs6XGZFI8ayHf68-WD-tAPeCZeAX2rFfKeMPq3iSHCWZgI_QyEOxuVjJ2XXhUdClRzYUtfXR5g",
            sheet_id = "tlHpWX",
            record_ids = new List<string>() { recordId },
        };
        var temp = JsonConvert.SerializeObject(content1);

        var content = new StringContent(
            JsonConvert.SerializeObject(content1),
            System.Text.Encoding.UTF8,
            "application/json");

        var wxResponse = await _qywxBaseService.QywxDocumentPost<SaveDigitalizationDemandRecordDetail>(content, "https://qyapi.weixin.qq.com/cgi-bin/wedoc/smartsheet/get_records?access_token=");
        if (wxResponse.records.Count > 0)
        {
            foreach (var item in wxResponse.records)
            {
                var current = string.Empty;
                if (item.values.当前状态 != null)
                {
                    current = item.values.当前状态[0].text;
                }
                var tempItem = new DigitalizationDemandEntity()
                {
                    Id = ToolHelper.GUIDTO16(),
                    Is_Deleted = 0,
                    Created_On = DateTime.Now,
                    Modified_On = DateTime.Now,
                    Record_Id = item.record_id,
                    Current_Status = getStatus(current),
                };
                //CsvList.Add(tempItem);

                result = await CheckDateBase(tempItem);
            }

            result = await GetHasFinishedNumber();

            return result;
        }

        return result;
    }

    /// <summary>
    /// 检查现有的数据条目
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> CheckDateBase(DigitalizationDemandEntity request)
    {
        var result = new CommonResponse();

        //var entity = new DocumentSafeRecordEntity();

        var sqlbuilder = new SqlBuilder();
        var sql = @"SELECT *
                    FROM digitalization_demand WHERE 1 = 1 AND is_deleted = 0 ";
        sqlbuilder.Add(" AND record_id = @RecordId ", "@RecordId", request.Record_Id);

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<DigitalizationDemandEntity>(sql, sqlbuilder);

        if (entity != null)
        {
            if (entity.Current_Status != request.Current_Status)
            {
                entity.Current_Status = request.Current_Status;
                result = await SaveDocumentToDateBase(entity, 1);
            }
            result.SetSuccess();
        }
        else
        {
            result = await SaveDocumentToDateBase(request, 0);
        }

        return result;
    }

    /// <summary>
    /// 保存到数据库
    /// </summary>
    /// <param name="request"></param>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<CommonResponse> SaveDocumentToDateBase(DigitalizationDemandEntity request, int type)//0新增，1修改
    {
        var result = new CommonResponse();
        var sql = string.Empty;
        var sqlbuilder = new SqlBuilder();
        sqlbuilder.Add("", "@Id", request.Id);
        sqlbuilder.Add("", "@IsDeleted", request.Is_Deleted);
        sqlbuilder.Add("", "@RecordId", request.Record_Id);
        sqlbuilder.Add("", "@CurrentStatus", request.Current_Status);

        if (type == 0)
        {
            sql = @$"INSERT INTO digitalization_demand (
    id, 
    created_on, 
    is_deleted, 
    record_id, 
    current_status
) VALUES (
    @Id, 
    @CreatedOn, 
    @IsDeleted, 
    @RecordId, 
    @CurrentStatus
);";
            sqlbuilder.Add("", "@CreatedOn", request.Created_On);
        }
        else
        {
            sql = $@"UPDATE digitalization_demand 
SET 
    modified_on = @ModifiedOn,
    is_deleted = @IsDeleted,
    record_id = @RecordId,
    current_status = @CurrentStatus
WHERE id = @Id;";
            sqlbuilder.Add("", "@ModifiedOn", request.Modified_On);
        }

        result = await _dateBaseService.ExecuteAsync(sql, sqlbuilder);
        return result;
    }

    public int getStatus(string item)
    {
        var res = 9;
        switch (item)
        {
            case "已处理":
                res = 0;
                break;
            case "未处理":
                res = 1;
                break;
            case "处理中":
                res = 2;
                break;
            default:
                res = 9;
                break;
        }
        return res;
    }

    /// <summary>
    /// 获取已完成需求数
    /// </summary>
    /// <returns></returns>
    public async Task<CommonResponse> GetHasFinishedNumber()
    {
        var result = new CommonResponse();

        var sqlbuilder = new SqlBuilder();
        var sql = @"SELECT 
count(record_id) as `Total`,
count(IF(current_status = 2, 1, NULL)) AS `Processing`,
count(IF(current_status = 0, 1, NULL)) AS `IsFinished`
FROM digitalization_demand WHERE 1 = 1 AND is_deleted = 0 ";

        var entity = await _dateBaseService.QueryFirstOrDefaultAsync<GetIsFinishedResponse>(sql, sqlbuilder);

        var updateDetail = new QywxTotalModel()
        {
            agentid = "1000173",
            secret = "Ip8TTg8gpHbx_4gOIJphFENjkuLqzLnDaS90TJ4BvNs",
            type = "keydata",
            userid_list = new List<string>(),
            keydata = new keydataDetail<keydataItemsDetail>()
            {
                items = new List<keydataItemsDetail>()
            }
        };
        var temp = new keydataItemsDetail()
        {
            key = "需求总量",
            data = entity.Total.ToString(),
            jump_url = "https://doc.weixin.qq.com/smartsheet/s3_AKoAgBSGAPQCNtaP5DoLcRHGkyHsD_a?scode=AGEATAfQAAc3EBD1zsAKoAgBSGAPQ&version=5.0.0.8619&platform=win&tab=tlHpWX&viewId=fv1"
        };
        var temp1 = new keydataItemsDetail()
        {
            key = "处理中",
            data = entity.Processing.ToString(),
            jump_url = "https://doc.weixin.qq.com/smartsheet/s3_AKoAgBSGAPQCNtaP5DoLcRHGkyHsD_a?scode=AGEATAfQAAc3EBD1zsAKoAgBSGAPQ&version=5.0.0.8619&platform=win&tab=tlHpWX&viewId=fv1"
        };
        var temp2 = new keydataItemsDetail()
        {
            key = "已完成需求",
            data = entity.IsFinished.ToString(),
            jump_url = "https://doc.weixin.qq.com/smartsheet/s3_AKoAgBSGAPQCNtaP5DoLcRHGkyHsD_a?scode=AGEATAfQAAc3EBD1zsAKoAgBSGAPQ&version=5.0.0.8619&platform=win&tab=tlHpWX&viewId=fv1"
        };
        updateDetail.keydata.items.Add(temp);
        updateDetail.keydata.items.Add(temp1);
        updateDetail.keydata.items.Add(temp2);

        result = await _netUpdateService.UpdateQywx(updateDetail);

        return result;
    }

    #endregion
}